package com.sencorsta.ids.core.application.proxy;

import com.sencorsta.ids.core.application.Application;
import com.sencorsta.ids.core.application.master.MasterClient;
import com.sencorsta.ids.core.function.SynFunction;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;


/**
 *
 * @author ICe
 */
/**
　　* @description: 代理会话处理程序
　　* @author TAO
　　* @date 2019/6/12 17:28
　　*/
@Sharable
public class ProxySessionHandler extends ChannelInboundHandlerAdapter {

	public ProxySessionHandler() {
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		Out.debug("proxy连接出现异常，Session:", ctx.channel().remoteAddress(), "; Exception:", cause.getMessage());

		ctx.channel().close();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object packet) throws Exception {
		RpcMessage msg=(RpcMessage) packet;
		Out.debug("proxy收到回调消息 ","msgId:",msg.msgId, "msg:",msg.toStringPlus());
		if (msg.msgId>0){
            SynFunction.response(msg.msgId,msg);
		}else if (msg.msgId<0){
			//异步调用无需返回
			return;
		}else {
			Application.getInstance().sendOpenMessage(msg);
		}
		//ProxyClient.handle((Packet) msg);
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		Out.debug("proxy通道被关闭,Session:",ctx.channel().remoteAddress());
		ctx.channel().close();
		//重新获取服务器列表
		MasterClient.getInstance().getTotalServer();
		//ProxyClient.close(ctx.channel());
	}

}
